package com.qf.smartplatform.exent.listener;/*
*王浩政 
*whz
2022/9/13
11:30
*小米商城
*/

import com.qf.smartplatform.exent.LoginEvent;
import com.qf.smartplatform.service.UserService;
import com.qf.smartplatform.utils.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Component
public class LoginEventListener {

//    private UserService userService;
//
//    @Autowired
//    public void setUserService(UserService userService){
//        this.userService=userService;
//    }

    private TaskExecutor taskExecutor;

    @Autowired
    public void setTaskExecutor(TaskExecutor taskExecutor){
        this.taskExecutor=taskExecutor;
    }

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService){
        this.userService=userService;
    }

   // @Async//异步执行
    @EventListener
    public void onEvent(LoginEvent event) throws InterruptedException {
        Thread.sleep(1000);
        System.out.println(Thread.currentThread().getName());
//        userService.updateLoginData(event.getUId(),event.getIp());
        //userService.updateLoginData(event.getuId(),event.getIp());
        //获取到request
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //根据浏览器来获取user-agent获取用户的浏览器，操作系统
        Map<String, String> osAndBrowserInfo = RequestUtil.getOsAndBrowserInfo(request);
        String sessionId = request.getSession().getId();
        String ip = request.getRemoteHost();
        //异步执行
        CompletableFuture.runAsync(()->{

            //更新登录的时间和ip
            userService.updateLoginData(event.getuId(),ip);
        },taskExecutor);
//        //获取系统和浏览器的信息
//        String os = osAndBrowserInfo.get("os");
//        String browser = osAndBrowserInfo.get("browser");
//        System.out.println(os);
//        System.out.println(browser);

        CompletableFuture.runAsync(()->{
           //获取系统和浏览器的信息
       String os = osAndBrowserInfo.get("os");
       String browser = osAndBrowserInfo.get("browser");
       System.out.println(os);
       System.out.println(browser);
       //根据ip获取地址
       String locationByIp = RequestUtil.getLocationByIp(ip);
       System.out.println(locationByIp);
       //TODO 将数据插入到数据库中，注意，理论上一个用户名应该只有一行数据

        },taskExecutor);


    }
}
